package cn.stylefeng.guns.modular.packreview.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.base.shiro.ShiroUser;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.modular.basic.entity.BasicAddress;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.model.params.BasicGoodsParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicWarehouseParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicGoodsResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicWarehouseResult;
import cn.stylefeng.guns.modular.basic.model.result.JHZYJDResult;
import cn.stylefeng.guns.modular.order.entity.OrderTransport;
import cn.stylefeng.guns.modular.order.entity.OutOrder;
import cn.stylefeng.guns.modular.order.entity.OutOrderExcelItem;
import cn.stylefeng.guns.modular.order.model.params.DealWithParam;
import cn.stylefeng.guns.modular.order.model.params.OrderTransportParam;
import cn.stylefeng.guns.modular.order.model.params.OutOrderDetailedParam;
import cn.stylefeng.guns.modular.order.model.params.OutOrderParam;
import cn.stylefeng.guns.modular.order.model.result.OrderTransportResult;
import cn.stylefeng.guns.modular.order.model.result.OutOrderResult;
import cn.stylefeng.guns.modular.packreview.entity.PackReview;
import cn.stylefeng.guns.modular.packreview.entity.PackReviewExcelItem;
import cn.stylefeng.guns.modular.packreview.mapper.PackReviewMapper;
import cn.stylefeng.guns.modular.packreview.model.params.PackReviewDetailsParam;
import cn.stylefeng.guns.modular.packreview.model.params.PackReviewParam;
import cn.stylefeng.guns.modular.packreview.model.result.PackReviewResult;
import cn.stylefeng.guns.modular.packreview.service.PackReviewDetailsService;
import  cn.stylefeng.guns.modular.packreview.service.PackReviewService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import static cn.stylefeng.guns.modular.location.excel.ExcelUtils.getCellValue;
import static cn.stylefeng.guns.sys.core.shiro.ShiroKit.getUser;

/**
 * <p>
 * 打包复核 服务实现类
 * </p>
 *
 * @author wp
 * @since 2025-07-05
 */
@Service
public class PackReviewServiceImpl extends ServiceImpl<PackReviewMapper, PackReview> implements PackReviewService {

    @Autowired
    private PackReviewDetailsService packReviewDetailsService;

    @Override
    public void add(PackReviewParam param){
        PackReview entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(PackReviewParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(PackReviewParam param){
        PackReview oldEntity = getOldEntity(param);
        PackReview newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public PackReviewResult findBySpec(PackReviewParam param){
        return null;
    }

    @Override
    public List<PackReviewResult> findListBySpec(PackReviewParam param){
        return this.baseMapper.customList(param);
    }

    @Override
    public LayuiPageInfo findPageBySpec(PackReviewParam param,String condition){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public ResponseData getExceldata(MultipartFile file, PackReviewParam packReviewParam, ResponseData data) throws IOException {

        String fileName = file.getOriginalFilename();

        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            data.setMessage("上传文件格式不正确");
            data.setSuccess(false);
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);

        List<PackReviewExcelItem> list = new ArrayList<PackReviewExcelItem>();
        for (int r = 1; r <= sheet.getLastRowNum()+1; r++) {
            Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }
            PackReviewExcelItem packReviewItem = new PackReviewExcelItem();
            String trackNumber = getCellValue(row.getCell(0));
            packReviewItem.setTrackNumber(trackNumber);//订单号

            String sendOutTime = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(1));
            packReviewItem.setSendOutTime(sendOutTime);//发货日期

            String goodsName = getCellValue(row.getCell(2));
            packReviewItem.setGoodsName(goodsName);//商品名称

            String goodsCode = getCellValue(row.getCell(3));
            packReviewItem.setGoodsCode(goodsCode);//商品编码

            // 根据天猫超市goodsCode()查询商品69码信息

            list.add(packReviewItem);
        }

        ShiroUser user = getUser();
        //主表信息
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Map<String, PackReviewExcelItem> trackNumberMap = list.stream()
                .collect(Collectors.toMap(PackReviewExcelItem::getTrackNumber, Function.identity(), (existing, replacement) -> existing)); // 使用自定义的合并函数来保持第一个遇到的元素（如果有重复的track number）
        List<PackReviewExcelItem> uniqueList = new ArrayList<>(trackNumberMap.values()); // 从Map中提取值列表作为结果列表


        for (PackReviewExcelItem packReviewItem : uniqueList) {
            PackReview packReview = new PackReview();
            String sendOutTime = packReviewItem.getSendOutTime();
            try {
                Date parse = simpleDateFormat.parse(sendOutTime);
                packReview.setSendOutTime(parse);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            packReview.setTrackNumber(packReviewItem.getTrackNumber());
            packReview.setPutCustomerId(packReviewParam.getPutCustomerId());
            packReview.setWarehouseId(packReviewParam.getWarehouseId());
            packReview.setDeptId(user.getDeptId());
            packReview.setCreateBy(user.getName());//创建人
            packReview.setCreateTime(new Date());
            this.save(packReview);
        }
        //子表信息
        for (PackReviewExcelItem packReviewItem : list) {
            PackReviewDetailsParam packReviewDetailsParam = new PackReviewDetailsParam();

            packReviewDetailsParam.setTrackNumber(packReviewItem.getTrackNumber());
            packReviewDetailsParam.setGoodsName(packReviewItem.getGoodsName());
            packReviewDetailsParam.setGoodsCode(packReviewItem.getGoodsCode());

            packReviewDetailsParam.setCreateBy(user.getName());//创建人
            packReviewDetailsParam.setCreateTime(new Date());
            packReviewDetailsService.add(packReviewDetailsParam);
        }
        data.setSuccess(true);
        data.setMessage("导入成功");
        return data;
    }

    @Override
    public void updateByTrackNumber(PackReviewParam packReviewParam) {
        this.baseMapper.updateByTrackNumber(packReviewParam);
    }

    @Override
    public void deleteByTrackNumber(String trackNumber) {
        this.baseMapper.deleteByTrackNumber(trackNumber);
    }

    @Override
    public void insertPackReview(PackReview packReview) {
        this.baseMapper.insertPackReview(packReview);
    }

    @Override
    public List<JHZYJDResult> findFhzyjdListByDeptId(Long deptId, String currentDate) {
        return this.baseMapper.findFhzyjdListByDeptId(deptId, currentDate);
    }

    private Serializable getKey(PackReviewParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private PackReview getOldEntity(PackReviewParam param) {
        return this.getById(getKey(param));
    }

    private PackReview getEntity(PackReviewParam param) {
        PackReview entity = new PackReview();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
